#include "ses_lcd.h"
#include "ses_led.h"
#include "timer/ses_timer.h"
#include "ses_adc.h"
#include "timer/ses_scheduler.h"
#include "datalogger.h"



volatile static uint16_t co2 = 0;
volatile static uint8_t temp = 0;



void read_Temp() {
	// initialize the ADC
	adc_init();

	// read and convert temperature
	temp = adc_convertTemp(adc_read(ADC_TEMP_CH));

	// set the prower reduction on
	adc_disable();

	// display temperature
	lcd_setCursor(0, 0);
	fprintf(lcdout, "actual:%dC", temp);
	put_temperature(temp);
	scheduler_add(read_Temp, ONE_SECOND);
}

void read_CO2() {
	// initialize the ADC
	adc_init();

	// read CO2
	co2 = adc_read(ADC_CO2_CH) * CO2_GAIN_ERR;
	if (co2 > THRESHOLD)
		co2 = THRESHOLD;

	// set the prower reduction on
	adc_disable();

	// display CO2
	lcd_setCursor(12, 0);
	fprintf(lcdout, "%4dppm \n", co2);

	led_redOff();
	led_yellowOff();
	led_greenOff();

	if (co2 < GREEN_LEVEL) {
		led_greenOn();
	} else if (co2 >= GREEN_LEVEL && co2 < YELLOW_GREEN_LEVEL) {
		led_greenOn();
		led_yellowOn();
	} else if (co2 >= YELLOW_GREEN_LEVEL && co2 < YELLOW_LEVEL) {
		led_yellowOn();
	} else if (co2 >= YELLOW_LEVEL && co2 < RED_YELLOW_LEVEL) {
		led_yellowOn();
		led_redOn();
	} else if (co2 >= RED_YELLOW_LEVEL) {
		led_redOn();
	}

	put_co2(co2);
	scheduler_add(read_CO2, ONE_SECOND);
}

void save() {
	save_to_eeprom();
	scheduler_add(save, FIVE_SECONDS);
}

void display_average() {
	getAverageValues();
	lcd_setCursor(0, 3);
	fprintf(lcdout, "Mean:%dC", DATA.avergTemp);
	lcd_setCursor(12, 3);
	fprintf(lcdout, "%dppm\n", DATA.avergCO2);

	scheduler_add(display_average, FIVE_SECONDS);
}

int main() {

	// initialize phase
	lcd_init();
	lcd_clear();
	led_allInit();
	scheduler_init();
	ext_eeprom_init();
	eeprom_init();

	/* This line is uncommented only to erase the data from the EEPROM */
	// forceInit();

	// initialize the EEPROM
	scheduler_add(read_CO2, IMMEDIATELY);
	scheduler_add(read_Temp, IMMEDIATELY);
	scheduler_add(save, IMMEDIATELY);
	scheduler_add(display_average, IMMEDIATELY);
	scheduler_run();

	return 0;
}
